package com.huatai.exchange.bootup.task;

import com.alibaba.fastjson.JSON;
import com.faneui.common.bean.BaseResp;
import com.faneui.common.utils.Constants;
import com.faneui.common.utils.DateFormatUtils;
import com.faneui.common.utils.ListUtils;
import com.faneui.service.Env;
import com.huatai.exchange.dal.model.ExcCustDataFile;
import com.huatai.exchange.dal.model.ExcFileLoadInfo;
import com.huatai.exchange.facade.Contents;
import com.huatai.exchange.integration.base.service.WorkDayService;
import com.huatai.exchange.integration.support.service.ScheduleBatchService;
import com.huatai.exchange.service.ExcCustDataFileService;
import com.huatai.exchange.service.ExcFileLoadInfoService;
import com.huatai.support.facade.bean.schedule.RegisterScheduleBatchReq;
import com.huatai.support.facade.enums.TaskScheduleType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AutoTask {

    private static final Logger logger = LoggerFactory.getLogger(AutoTask.class);

    @Autowired
    private ExcCustDataFileService custDataFileService;

    @Autowired
    private ScheduleBatchService scheduleBatchService;

    @Autowired
    private WorkDayService workDayService;

    @Value("${server.port}")
    private String businSystemCode;

    @Autowired
    private ExcFileLoadInfoService excFileLoadInfoService;

    @Autowired
    private Env env;

    @Scheduled(fixedDelay = 1000 *10 )
    public void run1() {
        if(!env.isProd()) {
            return;
        }
        logger.info("自动创建数据文件发送批次任务开始");
        BaseResp resp = new BaseResp();
        String  occurDate = DateFormatUtils.yyyyMMdd.format(new Date());
        try {
            ExcCustDataFile param = new ExcCustDataFile();
            param.setStatus(Constants.boolean_true);
            param.setNextDate(occurDate);
            List<ExcCustDataFile> tasks = custDataFileService.queryExcCustDataFileList(param);
            if (ListUtils.isNotEmpty(tasks)) {
                for (ExcCustDataFile task : tasks) {
                    // 校验 昨天的任务 是否执行 成功
                    createTaskBatch(task,occurDate);
                }
            }
        } catch (Exception ex) {
            logger.error("", ex);
            resp.setSuccess(false);
            resp.setMsg(ex.getMessage());
        }
        logger.info("自动创建数据文件发送批次任务结束");
    }

    /**
     *  10 秒钟处理
     */
    @Scheduled(fixedDelay = 1000 * 10 )
    public void run2() {
        if(!env.isProd()) {
            return;
        }
        logger.info("自动创建数据文件加载批次任务开始");
        BaseResp resp = new BaseResp();
        String occurDate = DateFormatUtils.yyyyMMdd.format(new Date());
        try{
            ExcFileLoadInfo param = new ExcFileLoadInfo();
            param.setNextDate(occurDate);
            param.setStatus(Constants.boolean_true);
            List<ExcFileLoadInfo> fileLoadInfos = excFileLoadInfoService.queryExcFileLoadInfoList(param) ;
            for (ExcFileLoadInfo loadInfo : fileLoadInfos) {
                // 判断时间是否在开始 加载
                try{
                    excFileLoadInfoService.createScheduleBatch(loadInfo,occurDate);
                } catch (Exception ex) {
                    logger.error("",ex);
                }
            }
        } catch (Exception ex) {
            logger.error("",ex);
            resp.setMsg(ex.getMessage());
            resp.setSuccess(false);
        }
        logger.info("自动创建数据文件加载批次任务结束");
    }



    private void createTaskBatch(ExcCustDataFile task,String occurDate){
        try {
            String startTime = task.getBeginTime();
            if (Integer.valueOf(DateFormatUtils.HHmmss.format(new Date())) < Integer.valueOf(startTime)) {
                logger.info("任务【{}】未到时间", task.getTaskName());
                return;
            }
            String jsonProperties = task.getJsonProperties();
            Map<String, Object> resvMap = JSON.parseObject(jsonProperties, HashMap.class);
            String interval = (String) resvMap.get("interval");
            //
            String nextDate = workDayService.getWorkDayNextWorkDay(occurDate);
            if (Contents.interval_first_workdate.equals(interval)) {
                nextDate = workDayService.getNextFirstWorkDay(occurDate);
            }

            RegisterScheduleBatchReq req = new RegisterScheduleBatchReq();

            req.setBusinId(Contents.busin_cust_data_id + task.getId());
            req.setTaskName(task.getTaskName());
            req.setBusinSystemCode(businSystemCode);
            // 参数编辑
            req.setProperties(task.getJsonProperties());
            req.setSystemPort(businSystemCode);
            req.setOccurDate(occurDate);
            req.setHttpMethod("GET");
            // 增加日期
            req.setInterfaceUrl(Contents.cust_excute_url + task.getId() + "?occurDate=" + occurDate);

            // 增加
            req.setTaskScheduleType(TaskScheduleType.day_more);

            if ("3".equals(task.getType())) {
                req.setDealInterval(10);   // 清算流程 10秒钟 间隔时间 ，1小时最大可执行 360
                req.setErrorTimes(360 * 6);       // 配置至少 6个小时
            } else {
                req.setDealInterval(10 * 60); // 秒为单位， 10 分钟 每天 可执行 144 次
                req.setErrorTimes(24 * 60 / 10);       // 默认  默认不超过 一天
            }

            scheduleBatchService.registerScheduleBatch(req);
            //  注册 任务

            custDataFileService.modifyCustDataFile(task.getId(), nextDate, occurDate);
        }catch (Exception ex) {
            logger.error("", ex);
        }
    }

}
